# -*- coding:utf-8 -*-
import builtins
import io

from PIL import ImageGrab

__author__ = 'gin.chen'
from aip import AipOcr
import os
import sys
import base64
import redis

r = redis.Redis(host='127.0.0.1', port=6379, db='0', password='foobared')

APP_ID = '16369236'
API_KEY = 'Fya9xgaNs11aYj7vXhkEQ4CV'
SECRET_KEY = 'NHYLtb6QcAdfR0GYfsOeQhTQjfbn3Ha0'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


def make_shot():
    box = (262, 562, 946, 601)
    im = ImageGrab.grab(box)
    # return im.tobytes()
    # im.save('path-to-save', 'png')
    imgByteArr = io.BytesIO()
    im.save(imgByteArr,format='PNG')
    imgByteArr = imgByteArr.getvalue()
    base64_data = base64.b64encode(imgByteArr)
    # print(base64_data)
    r.set("jpg_test", base64_data)
    print("存储完成")


def get_file_content():
    # with open(filePath, 'rb') as fp:
    var = r.get("jpg_test")
    print(var)
    data = base64.b64decode(var)
    return data


def execute_ocr():
    image = get_file_content()
    return client.basicGeneral(image)


if __name__ == '__main__':
    # image = os.path.abspath(os.path.dirname(sys.argv[0])) + '\\test2.jpg'
    # print(image)
    make_shot()
    res = execute_ocr()
    print(res)
    # window_capture('test.jpg')
    # box = (262, 562, 946, 601)
    # im = ImageGrab.grab(box)
    # # im.save('test2.jpg')
    # imgByteArr = io.BytesIO()
    # im.save(imgByteArr,format='PNG')
    # imgByteArr = imgByteArr.getvalue()
    #
    # res = client.basicGeneral(imgByteArr)
    # print(res)
